package cn.wolfcode.luowowo.website.util;

import cn.wolfcode.luowowo.cache.service.IUserinfoRedisService;
import cn.wolfcode.luowowo.member.domain.Userinfo;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

public class UserInfoAugumentResolver implements HandlerMethodArgumentResolver{

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType()== Userinfo.class && methodParameter.hasParameterAnnotation(UserInfoFromSpring.class);

    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        Cookie[] cookies = request.getCookies();
        Userinfo userinfo=null;
        for (Cookie cookie : cookies) {
            if("token".equals(cookie.getName())) {
                String value = cookie.getValue();
                String userinfo_str = redisTemplate.opsForValue().get(value);
                userinfo = JSON.parseObject(userinfo_str, Userinfo.class);
            }
        }
        return userinfo;
    }
}
